import { createAsyncThunk, createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState, AppThunk } from "../../app/store";

export interface TodoProps {
  id: number;
  text: string;
}
interface InitialProps {
  list: Array<TodoProps>; // TodoProps[]
}

const initialState: InitialProps = {
  list: [],
};

// 异步处理2
// createAsyncThunk 该函数用于简化 异步 action，接受两个参数
// 参数1：action 类型字符串
// 参数2：回调函数，必须返回 promise
export const addAsync2 = createAsyncThunk(
  "todo/addAsync2",
  async (payload: TodoProps) => {
    return new Promise<TodoProps>((resolve, reject) => {
      setTimeout(() => {
        resolve(payload);
      });
    });
  }
);

export const todoSlice = createSlice({
  name: "todo", // 命名空间，用于生成的 action type 的前缀的
  initialState, // 状态初始值
  reducers: {
    // 同步
    // 一个对象，用于更新 state 的函数
    // state 就是当前状态
    // action 就是触发当前状态更新的 action 对象，该对象携带的参数必须放在 payload 属性中
    add: (state, action) => {
      state.list.push(action.payload);
    },
    del: (state, action) => {
      state.list.splice(action.payload, 1);
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(addAsync2.pending, (state, action) => {
        console.log("pending状态", action);
      })
      .addCase(addAsync2.fulfilled, (state, action) => {
        console.log("fulfilled状态", action);
        state.list.push(action.payload);
      })
      .addCase(addAsync2.rejected, (state, action) => {
        console.log("rejected状态", action);
      });
  },
});

// 将 action 暴露出去，方便在组件中引用
export const { add, del } = todoSlice.actions;

// 异步处理1
export const addAsync =
  (amount: TodoProps): AppThunk =>
  (dispatch) => {
    setTimeout(() => {
      dispatch(add(amount));
    }, 1000);
  };

export default todoSlice.reducer;
